<template>
	<div class="register">
			<el-form :model="user" status-icon :rules="rules" ref="user" label-width="100px" class="demo-ruleForm">
			<el-form-item prop='username'>
				<span>用<i class='marginHalf'></i>户<i class='marginHalf'></i>名</span>
				<el-input v-model="user.username" maxlength="15" show-word-limit @blur='checkName'></el-input>
			</el-form-item>
			<el-form-item prop='email'>
				<span>电子邮箱</span>
				<el-input v-model="user.email" maxlength=50 show-word-limit></el-input>
			</el-form-item>
			<el-form-item prop='code'>
				<span>验<i class='marginHalf'></i>证<i class='marginHalf'></i>码</span>
				<div class="codeBox">
					<el-button class='sendCodeBtn' @click='sendCodeByEmail' :loading="loading" :disabled='disabledSendCode'>
						<span v-show='countDown'>
							{{countDown+'秒后'}}
						</span>发送验证码
			   	 	</el-button>
					<el-input v-model="user.code" maxlength=6></el-input>
				</div>
			</el-form-item>
			<el-form-item prop='password'>
				<span>密<i class='marginTwo'></i>码</span>
				<el-input type="password" v-model="user.password" show-password></el-input>
			</el-form-item>
			<el-form-item prop='checkPass'>
				<span>确认密码</span>
				<el-input type="password" v-model="user.checkPass" show-password></el-input>
			</el-form-item>
			<el-popover
			    placement="top-start"
			    title="提示"
			    width="300"
			    trigger="hover">
		   		<p>
			   	 	1.用户名最少3位字符，最多15位字符。<br> 
			   		2.邮箱请务必填写真实的并且是自己在使用的邮箱，找回密码时会用到，注册用户成功后邮箱不能更改。<br> 
			   		3.密码最少3位字符，最多16位字符
		   		</p>
		    	<el-link type="info" slot="reference">温馨提示</el-link>
		 	</el-popover>
			<div class='bottom'>
				<el-button type="primary"  @click="register('user')" >创建账户</el-button>
				<el-button @click="closeDialog">取 消</el-button>
				<p>
					已经有了一个账户?
					<el-link type="success" @click="fastLogin()">立刻登录</el-link>
				</p>
			</div>
		</el-form>
	</div>
</template>
<script>
	import {api} from '@/api/public'
	export default{
		name:'register',
		data(){
			let validateName = (rule, value, callback) => {
				if (value === '') callback(new Error('请输入用户名'));
				else if(value.length <3 || value.length>15) callback(new Error('用户名的长度不能小于3个字符，不能超过15个字符'));
				else callback();
			};
			let validateEmail = (rule, value, callback) => {
				if (value === '') callback(new Error('请输入邮箱地址'));
				else callback();
			};
			let validateCode = (rule, value, callback) => {
				if (value === '') callback(new Error('请输入验证码'));
				else callback();
			}
			let validatePass = (rule, value, callback) => {
				if (value === '') callback(new Error('请输入密码'));
				else if(value.length <3 || value.length>15) callback(new Error('密码的长度不能小于3个字符，不能超过16个字符'));
				else callback();
			};
			let validatePass2 = (rule, value, callback) => {
				if (value === '') callback(new Error('请再次输入密码'));
				else if (value !== this.user.password) callback(new Error('两次输入密码不一致!'));
				else callback();
			};
			return{
				existEmail:false,
				existName:false,
				prompt:'',
				timer:null,
				disabledSendCode:true,
				countDown:0,
				loading:false,
				user: {
					username:'',
		          	password: '',
		          	email:'',
		          	checkPass: '',
		          	code:''
		        },	
		        rules:{
		        	username:[{validator:validateName}],
		        	email:[
				      	{ validator:validateEmail},
				      	{ type: 'email', message: '请输入正确的邮箱地址'}
				    ],
				    code:[{validator:validateCode}],
		        	password:[
		        		{ validator: validatePass}
		        	],
		        	checkPass: [
		        		{ validator: validatePass2}
		        	]
		        }
			}
		},
		watch:{
			'user.email': {
				handler: function(val) {
					if(this.timer) return;
					let reg=/^([a-zA-Z\d])(\w|\-)+@[a-zA-Z\d]+\.[a-zA-Z]{2,4}$/;
					this.disabledSendCode=reg.test(val)?false:true;
				}
			}
		},
		methods:{
			fastLogin(){
				this.reset('changeCom','login');
			},
			closeDialog(){
				this.reset('closeDialog');
			},
			reset(methodName,params){
				let {username,email,code,password,checkPass}=this.user;
				if(username || email ||  code || password || checkPass){
					this.$confirm('离开注册时并不会保留你所写的内容，确认关闭吗', '提示', {
			          confirmButtonText: '确定',
			          cancelButtonText: '取消',
			          type: 'warning'
			        }).then(() => {
			         this.$emit(methodName,params);
			        }).catch(() => {});
				}
				else this.$emit(methodName,params);
			},
			async checkName(){
				let {count}=await api('post','user','checkInfo',{info:this.user.username,type:'name'});
				if(count>0){
					this.info('该用户名已被使用，请重新填写~~~','w');
					this.existName=true;
				}
				else this.existName=false;
			},
			async sendCodeByEmail(){
				if(this.timer) return this.info(`${this.countDown}秒后再点击发送验证码~~~`,'w');  
				let {email}=this.user;
				if(!email) return this.info('邮箱不能为空','w');
				if(this.disabledSendCode) return this.info('邮箱格式不正确','w');
				let {count}=await api('post','user','checkInfo',{info:email,type:'email'});
				if(count>0){
					this.info('该邮箱已被使用，请重新填写~~~','w');
					this.existEmail=true;
					return;
				}
				this.loading=true;
				this.existEmail=false;
				let {success}=await api('post','user','sendCodeByEmail',{contact:email,type:0});
				setTimeout(()=>{
					this.loading=false;
				},400);	
				if(success){
					this.info('验证码发送成功，请及时查看');
					this.countDown=60;
					this.timer=setInterval(()=>{
						this.countDown--;
						if(this.countDown==0){
							clearInterval(this.timer);
							this.timer=null;
							this.disabledSendCode=false;
							api('delete','user','deleteCode',{contact:email});
						}
					},1000)
					this.disabledSendCode=true;
				}
				else this.info('验证码发送失败~~~','e');
			},
			async register(formName){
				this.$refs[formName].validate(async (valid) => {
					if (valid) {
						if(this.existName) this.info('用户名已被使用，不能完成注册','w');
						else if(this.existEmail) this.info('邮箱已被使用，不能完成注册','w');
						else if(!this.disabledSendCode) return this.info('还没发送验证码呢','w');
						else{
							let {username,password,email,code}=this.user;
							let {success:s}=await api('post','user','checkCode',{contact:email,code:code});
							if(!s) return this.info('验证码错误，请重新输入~~~','e');
							let obj={
								username:username,
								password:password,
								email:email
							}
							let {success}=await api('post','user','register',obj);
							if(success){
								this.info('注册成功~~~');
								clearInterval(this.timer);
								this.timer=null;
								await api('delete','user','deleteCode',{contact:email});
								this.$emit('changeCom','login');
							}
							else this.info('注册失败~~~','e');
						}
					}
				})
			}
		}
	}
</script>
<style lang='stylus' scoped>
	.register{
		>>>.el-form-item__content{
			>span{
				margin-right: 0.5em;
			}
			>.el-input,.codeBox,.el-select{
				width:77%;
			}
			.codeBox{
				display:inline-block;
				position:relative;
			}
			.el-form-item__error{
				left:20%;
			}
		}
	}
</style>